<template>
  <div>
    <city-header></city-header>
    <city-search :cities="data.cities"></city-search>
    <city-list
      :hotCities="data.hotCities"
      :cities="data.cities"
      :letter="letter"
      :letters="letters"
    ></city-list>
    <city-alphabet :letters="letters" @change="letterChanged"></city-alphabet>
  </div>
</template>

<script>
import CityHeader from "./components/Header";
import CitySearch from "./components/Search";
import CityList from "./components/List";
import CityAlphabet from "./components/Alphabet";
import axios from "axios";
import { computed, onMounted, reactive, ref } from "vue";
export default {
  name: "City",
  components: {
    CityHeader,
    CitySearch,
    CityList,
    CityAlphabet,
  },
  setup() {
    const { letter, letterChanged } = useLetterLogic();
    const { data, letters } = getDataAndLetters();

    return { data, letter, letters, letterChanged };
  },
};

function useLetterLogic() {
  const letter = ref("");
  function letterChanged(selected) {
    letter.value = selected;
  }
  return { letter, letterChanged };
}

function getDataAndLetters() {
  const data = reactive({
    hotCities: [],
    cities: {},
  });

  const letters = computed(() => {
    const letters = [];
    for (let item in data.cities) {
      letters.push(item);
    }
    return letters;
  });

  async function getCityInfo() {
    let res = await axios.get("/api/city.json");
    res = res.data;
    if (res.ret && res.data) {
      const result = res.data;
      data.cities = result.cities;
      data.hotCities = result.hotCities;
    }
  }

  onMounted(() => {
    getCityInfo();
  });
  return { data, letters };
}
</script>

<style>
</style>